<template>
    <div class="rx-image">
        <uni-file-picker
            ref="image"
            v-model="files"
            :image-styles="imageStyles"
            :readonly="readOnly"
            :limit="fileLimit"
            mode="grid"
            :autoUpload="false"
            @select="selectFile"
        >
            <template #fileList v-if="metadata.options.showType==='carousel' && readOnly">
                <uni-swiper-dot @clickItem="clickItem" :info="files" :current="current" mode="round">
                    <swiper
                        :style="{'width':metadata.options.width || '200px','height':metadata.options.height || '200px'}"
                        @change="change" :current="swiperDotIndex">
                        <swiper-item v-for="(file, index) in files" :key="index">
                            <image class="file-image" :src="getImageUrl(file)" mode="aspectFill"
                                   @click.stop="previewImage(file,index)"></image>
                        </swiper-item>
                    </swiper>
                </uni-swiper-dot>
            </template>
            <template #file="{file,index}" v-else>
                <image class="file-image" :src="getImageUrl(file)" mode="aspectFill"
                       @click.stop="previewImage(file,index)"></image>
                        <span class="rx-image-del" v-if="!readOnly" @click="removeSelect(index)">
                        <my-icon type="icon-icon-test26"></my-icon>
                        </span>
            </template>
        </uni-file-picker>
    </div>
    <RxEmpty style="margin-top: 0.5rem" v-if="readOnly && files.length==0"></RxEmpty>
</template>
<script>
import MForm from '../js/MForm';
import {FormApi} from "@/api/FormApi.js";
import TokenUtil from "../../../../common/TokenUtil";
import RxEmpty from "@/components/RxEmpty"

export default {
    name: "MImage",
    mixins: [MForm],
    components:{RxEmpty},
    data() {
        return {
            current: 0,
            swiperDotIndex: 0,
            imageStyles: {
                width: this.metadata.options.width || 200,
                height: this.metadata.options.height || 200,
            },
            files: [],
            fileLimit: this.metadata.options.amount || 9,
        }
    },
    created() {
        this.initValue(this.value);
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "componentsLang", key);
        },
        change(e) {
            this.current = e.detail.current
        },
        clickItem(e) {
            this.swiperDotIndex = e
        },
        /**
         * 删除选测图片
         */
        removeSelect(idx) {
            this.files.splice(idx, 1);
        },
        selectFile(e) {
            let curFile = e.tempFiles[0];
            if ((curFile.size / (1024 * 1024)) > this.metadata.options.size) {
                uni.showToast({
                    title: this.i18n('pictures', '上传图片大于指定大小') + this.metadata.options.size + "M！",
                    duration: 1500,
                    icon: 'none'
                });
                this.$refs.file.clearFiles(this.files.length - 1);
                return;
            }
            var imageSrc = e.tempFilePaths[0];
            FormApi.upload({
                filePath: imageSrc,
                fileType: 'image'
            }).then(res => {
                this.handFiles(res.data);
            })
        },
        getImageUrl(file) {
            if(file && file.url){
                return file.url
            }
            let fileId = file.fileId;
            let token = TokenUtil.getToken();
            return this.realUrl() + "/api-system/system/core/sysFile/downloadScale/" + fileId + "?accessToken=" + token;
        },
        previewImage(file, index) {
            let urls = [];
            this.files.forEach(item => {
                urls.push(this.imageUrl(item.fileId))
            })
            uni.previewImage({
                urls: urls,
                current: index
            });
        },
        initValue(val) {
            if (!val) return [];
            var fileAry = JSON.parse(val);
            this.files = fileAry;
        },
        handFiles(json) {
            var aryFiles = json.data;
            for (var i = 0; i < aryFiles.length; i++) {
                var file = aryFiles[i];
                this.files.push({
                    extname: file.ext,
                    fileId: file.fileId,
                    size: file.totalBytes,
                    fileName: file.fileName,
                    fileSystem: file.fileSystem,
                    path: file.path,
                    createUser: file.createUser,
                    createTime: file.createTime
                });
            }
        },

    },
    watch: {
        files: {
            handler(newValue, oldValue) {
                var str = JSON.stringify(newValue);
                this.updateValue(str);
                this.triggerEmitEvents('change', str, this.data)
            },
            deep: true
        },
        value: function (val, oldVal) {
            if (val != oldVal) {
                this.initValue(val);
            }
        }
    }
}
</script>

<style scoped>
.file-image {
    width: 100%;
    height: 100%;
}

.rx-image-del {
    position: absolute;
    right: -0.7rem;
    top: -0.8rem;
}

.rx-image-del i {
    color: red;
    font-size: 1.2rem;
    z-index: 99;
}
.rx-image  >>>.file-picker__box-content,.rx-image>>>.uni-file-picker {
    overflow: initial!important;
}
.rx-image>>>.file-picker__box{
    margin-right: 0.5rem;
    width: 5rem!important;
    height: 5rem!important;
    border-radius: 0.5rem;
}
</style>
